import 'package:flutter/material.dart';

class CustomStatefulWidget extends StatelessWidget {
  const CustomStatefulWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          leading: IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(Icons.arrow_back),
          ),
          // centerTitle: true,
          // backgroundColor: Colors.blue[500
          title: const Text('学习statefulWidget'),
          centerTitle: true,
          backgroundColor: Colors.amber[800]),
      body: CustomStatefulBody(),
    );
  }
}

class CustomStatefulBody extends StatefulWidget {
  CustomStatefulBody({super.key}) {
    print('CustomStatefulBody 构造函数创建了');
  }
  @override
  State<CustomStatefulBody> createState() {
    print('createState 被执行了');
    return _CustomStatefulBodyState();
  }
}

class _CustomStatefulBodyState extends State<CustomStatefulBody> {
  int counter = 0;
  // 当StatefulWidget首次被插入到widget树中时，会调用此方法。它负责创建State对象。
  @override
  void initState() {
    print('initState 被执行了');
    super.initState();
  }

  // 当State对象的依赖关系发生变化时，会调用此方法。这包括当此State对象被插入到树中时，以及当widget的依赖项发生变化时。
  @override
  void didChangeDependencies() {
    print('didChangeDependencies 被执行了');
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(covariant CustomStatefulBody oldWidget) {
    print('didUpdateWidget 被执行了');
    super.didUpdateWidget(oldWidget);
  }

  void removeCounter() {
    setState(() {
      counter--;
    });
  }

  void addCounter() {
    setState(() {
      counter++;
    });
  }

  // 当需要重新构建此StatefulWidget时，会调用此方法。它负责构建并返回代表此StatefulWidget的视图。
  @override
  Widget build(BuildContext context) {
    return Center(
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('$counter'),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // onPressed:null,代表disabled 反之则可以正常使用
            FilledButton(
              onPressed: counter == 15 ? null : addCounter,
              child: const Icon(Icons.add),
            ),
            const SizedBox(
              width: 10,
            ),
            FilledButton.tonal(
              onPressed: counter == 0 ? null : removeCounter,
              child: const Icon(Icons.remove),
            ),
          ],
        )
      ],
    ));
  }

  @override
  void deactivate() {
    super.deactivate();
    print('deactivate');
  }

  @override
  void dispose() {
    super.dispose();
    print('dispose');
  }
}
